package main

import (
	"fmt"
	"log"
	"os"

	"../pb"
	"../util"
	"golang.org/x/net/context"
)

const (
	FILE_NOTFINISHED = int64(1)
	FILE_FINISHED    = int64(2)
)

const (
	OK    = int64(4)
	ERROR = int64(5)
)

type Client struct {
	client pb.RfdServiceClient
}

func (c *Client) Download(path, latnId string, file *os.File) error {
	ftclient, err := c.client.FileTransfer(context.Background())
	if err != nil {
		return fmt.Errorf("Client.Download.FileTransfer: %v", err)
	}
	request := &pb.FileTransferRequest{
		FilePath: path,
		LatnId:   latnId,
	}
	if err = ftclient.Send(request); err != nil {
		return fmt.Errorf("Client.Download.Send: %v", err)
	}
	for {
		resp, err := ftclient.Recv()
		if err != nil {
			return fmt.Errorf("Client.Download.Recv: %v", err)
		}
		switch resp.State {
		case FILE_NOTFINISHED:
			if util.MD5(resp.FileData) != resp.CheckSum {
				log.Println("[Error] MD5校验失败，请求重传： %s", path)
				request := &pb.FileTransferRequest{State: ERROR}
				ftclient.Send(request)
				continue
			}
			if _, err := file.Write(resp.FileData); err != nil {
				log.Printf("[Error] 文件写入失败: %s", file.Name())
				return fmt.Errorf("Client.Download.WriteFile: %v", err)
			}
			request := &pb.FileTransferRequest{State: OK}
			ftclient.Send(request)
		case FILE_FINISHED:
			request := &pb.FileTransferRequest{State: OK}
			ftclient.Send(request)
			ftclient.CloseSend()
			return nil
		}
	}
	return nil
}
